package info.maxhis.bn.birthday;

import info.maxhis.bn.ContactsAdapter;
import info.maxhis.bn.R;
import info.maxhis.entity.Friend;
import info.maxhis.service.FriendService;
import info.maxhis.util.CalendarUtil;
import info.maxhis.util.SharedData;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

/**
 * 新增生日信息
 * @author iStar
 *
 */
public class AddBirthdayActivity extends Activity implements OnCheckedChangeListener {
	private AutoCompleteTextView nameView;
	private EditText phoneNumView;
	private DatePicker datePicker;
	private Button saveButton;
	private FriendService fs;
	private RadioGroup dateTypeGroup;
	private Cursor cursor;
	private ContactsAdapter cAdapter;
	private SharedData share;
	private int dateType = CalendarUtil.DATE_TYPE_SOLAR;
//	private int mYear,mMonth,mDay;
	
	//要获取的通讯录字段
	public static final String[] PEOPLE_PROJECTION = new String[]{
		ContactsContract.Contacts._ID,
		ContactsContract.CommonDataKinds.Phone.NUMBER,
		ContactsContract.Contacts.DISPLAY_NAME
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_add_birthday);
		fs = new FriendService(this);
		share = new SharedData(this);
		
		findViews();
		autoComplete();	//自动补充姓名和号码
		bindViews();
	}

	private void bindViews() {
		
		saveButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
	
				String nameStr = nameView.getText().toString().trim();
				if (nameStr == null || nameStr.equals("")) {
					nameView.setError(AddBirthdayActivity.this.getResources().getString(R.string.name_needed));
//					Toast.makeText(AddBirthdayActivity.this, R.string.name_needed, Toast.LENGTH_SHORT).show();
					return ;
				}
				String phone = phoneNumView.getText().toString().trim();
				Friend f = new Friend();
				f.setDateType(dateType);
				f.setName(nameStr);
				f.setPhone(phone);
				datePicker.invalidate();
//				Log.d("TAG", "year:" + datePicker.getYear());
//				Log.d("TAG", "month:" + (datePicker.getMonth()+1));
//				Log.d("TAG", "day:" + datePicker.getDayOfMonth());
				
				f.setBirthYear(datePicker.getYear());
				f.setBirthMonth(datePicker.getMonth()+1);//
				f.setBirthDay(datePicker.getDayOfMonth());
				if (fs.addFriend(f)) {
					//检查是否当天生日,若是，产生提醒
					if (CalendarUtil.daysLeft2Birthday(f) - share.getAdvanceTime() <= 0) {
						share.makeNotification(f);
					}
					AlertDialog.Builder builder = new AlertDialog.Builder(AddBirthdayActivity.this);
					builder.setMessage(R.string.continue_add)
							.setIcon(R.drawable.ask).setTitle(R.string.add_success)
							.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									Intent intent = new Intent(AddBirthdayActivity.this, AddBirthdayActivity.class);
									startActivity(intent);
									AddBirthdayActivity.this.finish();
								}
							})
							.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									AddBirthdayActivity.this.finish();
								}
							});
					AlertDialog alert = builder.create();
					alert.show();
				}
				
				//添加到Google Calendar
				if (fs.addToGoogle(f)) {
					Toast.makeText(AddBirthdayActivity.this, nameStr + "生日信息已添加到Google Calendar", 
							Toast.LENGTH_SHORT).show();
				}
			}
		});
	}
	
	/**
	 * 自动补充姓名和号码
	 */
	private void autoComplete() {
		ContentResolver resolver = getContentResolver();
		cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PEOPLE_PROJECTION, null, null, "");
		cAdapter = new ContactsAdapter(this, cursor);
		nameView.setAdapter(cAdapter);
		nameView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				/* 取得Cursor */
				Cursor c = cAdapter.getCursor();
				/* 移到所点击的位置 */
				c.moveToPosition(position);
				String number = c.getString(c
						.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
				
				number = (number == null ? "" : number);
				phoneNumView.setText(number);
			}
			
		});
	}

	private void findViews() {
		nameView = (AutoCompleteTextView) findViewById(R.id.friend_name);
		phoneNumView = (EditText) findViewById(R.id.phone_num);
		saveButton = (Button) findViewById(R.id.add_birthday);
		datePicker = (DatePicker) findViewById(R.id.birthday_date_picker);
		dateTypeGroup = (RadioGroup) findViewById(R.id.dateTypeGroup);
		dateTypeGroup.setOnCheckedChangeListener(this);
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		if (checkedId == R.id.normal_date) {
			dateType = CalendarUtil.DATE_TYPE_SOLAR;
		} else {
			dateType = CalendarUtil.DATE_TYPE_LUNDAR;
		}
	}

}
